<?php

namespace app\admin\controller\api;

use app\common\model;
use app\common\model\Classes;
use app\common\model\CourseDetail;

/**
 * 教师
 * @internal
 */
class Teacher extends Api
{
    protected $noNeedLogin = ['index', 'course', 'profile', 'getByCardNumber'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $id = $this->request->request('id', 0);
        $result = \app\common\model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('teacher.id', $id)
            ->field('teacher.*,user.nickname name,user.mobile,user.gender')
            ->find();

        if ($result) {
            $result = $result->append(['gender_text'])->toArray();
            if (!strstr($result['avatar'], 'http') && strstr($result['avatar'], 'uploads/')) {
                $result['avatar'] = config('app_url') . $result['avatar'];
            }
        }

        $this->success('', $result);
    }

    public function info()
    {
        $id = $this->request->request('id', 0);
        $result = \app\common\model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('teacher.id', $id)
            ->field('teacher.*,user.nickname name,user.mobile,user.gender')
            ->find();

        if ($result) {
            $result = $result->append(['gender_text'])->toArray();
            if (!strstr($result['avatar'], 'http') && strstr($result['avatar'], 'uploads/')) {
                $result['avatar'] = config('app_url') . $result['avatar'];
            }
        }

        $this->success('', $result);
    }

    /**
     * 根据ids获取教师信息
     */
    public function profile()
    {
        $teacher_ids = $this->request->post('ids/a');
        if (!$teacher_ids) {
            $this->error('参数有误');
        }

        $list = model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->whereIn('teacher.id', $teacher_ids)
            ->column('teacher.id,teacher.user_id,user.nickname name,user.mobile,user.avatar', 'teacher.id');

        foreach ($list as $key => $value) {
            if (!strstr($value['avatar'], 'http') && strstr($value['avatar'], 'uploads/')) {
                $list[$key]['avatar'] = config('app_url') . $value['avatar'];
            }
        }

        $this->success('', $list);

    }

    /**
     * 根据卡号获取教师信息
     *
     * @param card_number string 卡号
     * @param school_id int 学校id 优先选用school_id 如果没有选用class_id去找school_id
     * @param class_id int 班级id
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getByCardNumber()
    {
        $card_number = $this->request->request('card_number');
        $school_id = $this->request->request('school_id', 0);
        $class_id = $this->request->request('class_id', 0);

        if (!$card_number) {
            $this->error('参数错误');
        }

        // 优先选用school_id 如果没有选用class_id去找school_id
        if (!$school_id) {
            if (!$class_id) {
                $this->error('参数错误');
            }
            $classes = Classes::get($class_id);
            if (!$classes) {
                $this->error('班级不存在');
            }
            $school_id = $classes->school_id;
        }

        $teacher = model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('teacher.card_number', $card_number)
            ->where('teacher.school_id', $school_id)
            ->field('teacher.id,teacher.card_number,user.nickname name,user.avatar,user.mobile,school_id')
            ->find();

        if (!$teacher) {
            $this->error('数据不存在');
        }
        $teacher->avatar = config('app_url') . $teacher->avatar;
        $this->success('', $teacher);
    }

    /**
     * 模糊搜索教师信息
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function search()
    {
        $keywords = $this->request->request('keywords');
        $list = model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('user.nickname|user.mobile', 'like', "%$keywords%")
            ->field('teacher.id')
            ->select();

        $teacher_ids = array_column($list, 'id');

        $this->success('', $teacher_ids);
    }

    /**
     * 课程表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function course()
    {
        $teacher_id = $this->request->request('id');

        $teacher = model\Teacher::get($teacher_id);
        if (!$teacher) {
            $this->error('教师不存在');
        }

        //教师任课
        $teaches = \app\common\model\Teach::alias('teach')
            ->join('__SUBJECT__ subject', 'subject.id = teach.subject_id')
            ->where('teach.school_id', $teacher->school_id)
            ->where('teach.teacher_id', $teacher_id)
            ->column('teach.id,teach.type,subject.name subject_name', 'teach.id');

        $teach_ids = array_keys($teaches);
        $course_details = [];
        $list = CourseDetail::whereIn('teach_id', $teach_ids)->select();

        if ($list) {
            $class_ids = array_column(Collection($list)->toArray(), 'class_id');
            $classes = Classes::alias('class')
                ->join('__GRADE__ grade', 'grade.id = class.grade_id')
                ->whereIn('class.id', $class_ids)
                ->column('class.id,class.name class_name,grade.name grade_name', 'class.id');

            foreach ($list as $key => $value) {
                if (isset($teaches[$value['teach_id']]) && isset($classes[$value['class_id']])) {
                    $course_details[$value['number']][$value['day']] = [
                        'class_name' => $classes[$value['class_id']]['class_name'],
                        'grade_name' => $classes[$value['class_id']]['grade_name'],
                        'subject_name' => $teaches[$value['teach_id']]['subject_name'],
                    ];
                }
            }
        }

        //所有课节
        $class_days = [];
        $list = \app\common\model\ClassDay::where('school_id', $teacher->school_id)->select();
        foreach ($list as $key => $class_day) {
            /*if (isset($course_details[$class_day['number']]) && isset($course_details[$class_day['number']][$class_day['day']])) {
                $class_days[$class_day['number']][$class_day['day']][] = $course_details[$class_day['number']][$class_day['day']];
            } else {
                $class_days[$class_day['number']][$class_day['day']] = [];
            }*/

            $class_days[$class_day['number']]['number'] = $class_day['number'];
            $class_days[$class_day['number']]['start_time'] = $class_day['start_time'];
            $class_days[$class_day['number']]['end_time'] = $class_day['end_time'];
            if (isset($course_details[$class_day['number']]) && isset($course_details[$class_day['number']][$class_day['day']])) {
                $temp_data = $course_details[$class_day['number']][$class_day['day']];
                $class_days[$class_day['number']]['data'][] = [
                    'subject_name' => $temp_data['subject_name'],
                    'grade_name' => $temp_data['grade_name'],
                    'class_name' => $temp_data['class_name'],
                ];
            } else {
                $class_days[$class_day['number']]['data'][] = [];
            }
        }
        $class_days = array_values($class_days);

        $this->success('', $class_days);
    }

    public function lists()
    {
        $where = $this->request->request('where');
        $sort = $this->request->request('sort');
        $order = $this->request->request('order');
        $offset = $this->request->request('offset');
        $limit = $this->request->request('limit');

        $school_ids = $this->getSchoolIds($this->_user['id']);
        $total = model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where($where)
            ->where(function ($query) use ($school_ids) {
                if (!in_array('*', $school_ids)) {
                    $query->whereIn('teacher.school_id', $school_ids);
                }
            })
            ->order($sort, $order)
            ->count();

        $list = model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where($where)
            ->where(function ($query) use ($school_ids) {
                if (!in_array('*', $school_ids)) {
                    $query->whereIn('teacher.school_id', $school_ids);
                }
            })
            ->field('teacher.*,user.nickname name,user.mobile,user.gender')
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        if ($list) {
            $list = collection($list)->append(['gender_text'])->toArray();
        }

        $result = array("total" => $total, "rows" => $list);

        $this->success('', $result);

    }
}